<?php

/**
 * TomatoCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: MailController.php 4522 2010-08-12 09:38:16Z huuphuoc $
 * @since		2.0.6
 */
class Mail_MailController extends Zend_Controller_Action {
    /* ========== Backend actions =========================================== */

    /**
     * List sent mails
     *
     * @return void
     */
    public function listAction() {
        $request = $this->getRequest();
        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 20;
        $offset = ($pageIndex - 1) * $perPage;

        //$user = Zend_Auth::getInstance()->getIdentity();
        $mailModel = Rabbit_Model_Factory::getInstance()->setModule('mail')->getMailModel();
        
        $params = null;
        $exp = array(
            //'created_user_id' => $user->id,
            'type' => 'mail',
            'folder' => 'inbox'
			
        );
        if ($request->isPost()) {
            $type = $request->getPost('type');
            $folder = $request->getPost('folder');
            $isRead = $request->getPost('is_read');
            $createdUserId = $request->getPost('created_user_id');
            

            if ($type) {
                $exp['type'] = $type;
            }
            if ($folder) {
                $exp['folder'] = $folder;
            }
            if ($isRead) {
                $exp['is_read'] = $isRead;
            }
            if($createdUserId)
                $exp['created_user_id'] = $createdUserId;
            
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        } else {
            $params = $request->getParam('q');
            if ($params != null) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }
       

        $mails = $mailModel->getMails($offset, $perPage, $exp);
        $numMails = $mailModel->count();

        /**
         * Paginator
         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($mails, $numMails));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);
		$this->view->assign('exp', $exp);
        $this->view->assign('mails', $mails);
        $this->view->assign('numMails', $numMails);
        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url(array(), 'mail_mail_list'),
            'itemLink' => 'page-%d',
        ));
    }

    /**
     * Send an email from front-end
     *
     * @return void
     */
    public function contactAction() {
        //$user = Zend_Auth::getInstance()->getIdentity();
        $this->view->headTitle($this->view->translate('mail_contact_page_title'));
        $request = $this->getRequest();
        if ($request->isPost()) {
            $recaptcha_challenge_field = $request->getPost('recaptcha_challenge_field');
            $recaptcha_response_field = $request->getPost('recaptcha_response_field');
            //check capcha first
            if (Rabbit_Recapcha::checkCapcha($recaptcha_challenge_field, $recaptcha_response_field)) {
                $subject = $request->getPost('subject');
                $content = $request->getPost('message');
                $fromName = $request->getPost('name');
                $fromMail = $request->getPost('email');
                $sendCopy   = $request->getPost('send_copy');
//
                /**
                 * Get mail transport instance
                 */
                $transport = Mail_Services_Mailer::getMailTransport();

                /**
                 * Send email to each user
                 * @see http://framework.zend.com/manual/en/zend.mail.multiple-emails.html
                 */
                $mailModel = Rabbit_Model_Factory::getInstance()->setModule('mail')->getMailModel();

                $config = Tomato_Module_Config::getConfig('mail');
                $toMail = $config->smtp->username;

                $mailModel->add(new Mail_Models_Entities_Mail(array(
                            'subject' => $subject,
                            'content' => $content,
                            'from_mail' => $fromMail,
                            'from_name' => $fromName,
                            'to_mail' => $toMail,
                            'status' => 'outgoing',
                            'created_date' => date('Y-m-d H:i:s'),
                            'sent_date' => date('Y-m-d H:i:s'),
                            'created_user_id' => 0,
                            'type' => 'mail'
                        )));

                $mail = new Zend_Mail();
                $mail->clearFrom()->setFrom($fromMail, $fromName)
                        ->addTo($toMail, '')
                        ->setSubject($subject)
                        ->setBodyHtml($content);
                        
                if($sendCopy){
                    $mail->addCc($fromMail, '');
                }
                $mail->send($transport);
//
                /**
                 * Redirect
                 */
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('success:' .$this->view->translate('mail_send_success'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'mail_mail_contact'));
            } else {
                /**
                 * Redirect
                 */
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:'. $this->view->translator('mail_contact_captcha_error'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'mail_mail_contact'));
            }
        }

    }

    public function detailsAction(){
        $request = $this->getRequest();
        $mailId = $request->getParam('id');
        $mailModel = Rabbit_Model_Factory::getInstance()->setModule('mail')->getMailModel();
        $mail = $mailModel->getById($mailId);
        if($mail == null){
            throw  new Exception('Error the mail with '. $mailId .' no exists');
        }
        $mailModel->updateRead($mailId);
        $this->view->assign('mail', $mail);
    }
    public function deleteAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        $result = array('status' => false, 'message' => null);
        if ($request->isPost()) {
            $id = $request->getPost('id');
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }

            $mailModel = Rabbit_Model_Factory::getInstance()->setModule('mail')->getMailModel();

            foreach ($ids as $mailId) {
                $mail = $mailModel->getById($mailId);
                if ($mail != null) {
                    if($mailModel->delete($mailId)){
                        $result['status'] = true;
                    }else{
                        $result['message'] = $this->_helper->getHelper('translate')->translate('mail_list_delete_error');
                    }
                }
            }
        }

        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

    /**
	 * Send an email
	 *
	 * @return void
	 */
	public function sendAction()
	{
		$user = Zend_Auth::getInstance()->getIdentity();

		$templateModel = Rabbit_Model_Factory::getInstance()->setModule('mail')->getTemplateModel();
		$roleModel     = Rabbit_Model_Factory::getInstance()->setModule('core')->getRoleModel();
            
		$templates = $templateModel->getTemplates($user->id);
		$roles 	   = $roleModel->getRoles();

		$request 	= $this->getRequest();
		$templateId = $request->getParam('template_id');
		$currentTemplate = ($templateId == null) ? null : $templateModel->getById($templateId);

		if ($request->isPost()) {
			/**
			 * Get the list of users
			 */
			$userDao = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserDao();
			$userDao->setDbConnection($conn);
			$roleId = $request->getPost('role');
			$exp    = ($roleId == '') ? array('status' => 1) : array('role' => $roleId, 'status' => 1);
			$users  = $userDao->find(null, null, $exp);

			$subject     = $request->getPost('subject');
			$content     = $request->getPost('content');
			$fromName    = $request->getPost('fromName');
			$fromMail    = $request->getPost('fromMail');
			$replyToName = $request->getPost('replyToName');
			$replyToMail = $request->getPost('replyToMail');

			/**
			 * Get mail transport instance
			 */
			$transport = Mail_Services_Mailer::getMailTransport();

			/**
			 * Send email to each user
			 * @see http://framework.zend.com/manual/en/zend.mail.multiple-emails.html
			 */
			$search = array(Mail_Models_Entities_Mail::MAIL_VARIABLE_EMAIL, Mail_Models_Entities_Mail::MAIL_VARIABLE_USERNAME);
			$mailDao = Rabbit_Model_Factory::getInstance()->setModule('mail')->getMailModel();

			foreach ($users as $u) {
				$replace = array($u->email, $u->username);
				$subject = str_replace($search, $replace, $subject);
				$content = str_replace($search, $replace, $content);

				$mailDao->add(new Mail_Models_Entities_Mail(array(
					'template_id' 	  => $templateId,
					'subject' 		  => $subject,
					'content' 		  => $content,
					'created_user_id' => $user->id,
					'from_mail' 	  => $fromMail,
					'from_name' 	  => $fromName,
					'reply_to_mail'   => $replyToMail,
					'reply_to_name'   => $replyToName,
					'to_mail' 		  => $u->email,
					'to_name'         => $u->username,
					'status' 		  => 'sent',
					'created_date'    => date('Y-m-d H:i:s'),
					'sent_date' 	  => date('Y-m-d H:i:s'),
				)));

				$mail = new Zend_Mail();
				$mail->clearFrom()->setFrom($fromMail, $fromName)
					->clearReplyTo()->setReplyTo($replyToMail, $replyToName)
					->addTo($u->email, $u->username)
					->setSubject($subject)
					->setBodyHtml($content)
					->send($transport);
			}

			/**
			 * Redirect
			 */
			$this->_helper->getHelper('FlashMessenger')
				->addMessage('error:'. $this->view->translator('mail_send_success'));
			$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'mail_mail_list'));
		}

		$this->view->assign('templates', $templates);
		$this->view->assign('currentTemplate', $currentTemplate);
		$this->view->assign('roles', $roles);
		$this->view->assign('email', $user->email);
		$this->view->assign('name', $user->full_name);
	}
        
	public function feedbackAction(){
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->getHelper('viewRenderer')->setNoRender();
		//$user = Zend_Auth::getInstance()->getIdentity();
		$request = $this->getRequest();
		
		$result = array(
					'message' => '',
					'status' => false
					);
					
		if ($request->isPost()) {
			$recaptcha_challenge_field = $request->getPost('recaptcha_challenge_field');
			$recaptcha_response_field = $request->getPost('recaptcha_response_field');
			//check capcha first
			if (Rabbit_Recapcha::checkCapcha($recaptcha_challenge_field, $recaptcha_response_field)) {
				$content = $request->getPost('message');
				$fromName = $request->getPost('name');
				$fromMail = $request->getPost('email');
				try{
					/**
					 * Get mail transport instance
					 */
					$transport = Mail_Services_Mailer::getMailTransport();

					/**
					 * Send email to each user
					 * @see http://framework.zend.com/manual/en/zend.mail.multiple-emails.html
					 */
					$mailModel = Rabbit_Model_Factory::getInstance()->setModule('mail')->getMailModel();

					$config = Tomato_Module_Config::getConfig('mail');
					$toMail = $config->smtp->username;

					$mailModel->add(new Mail_Models_Entities_Mail(array(
								'subject' => '',
								'content' => $content,
								'from_mail' => $fromMail,
								'from_name' => $fromName,
								'to_mail' => $toMail,
								'status' => 'outgoing',
								'created_date' => date('Y-m-d H:i:s'),
								'sent_date' => date('Y-m-d H:i:s'),
								'created_user_id' => 0,
								'type' => 'feedback',
								'folder' => 'inbox'
							)));

					$mail = new Zend_Mail();
					$mail->clearFrom()->setFrom($fromMail, $fromName)
							->addTo($toMail, '')
							->setSubject('FeedBack')
							->setBodyHtml($content);
					$mail->send($transport);
				}catch(Exception $ex){
					$result['message'] = $this->view->translate('mail_feedback_send_error');
					$result['status'] = false;
				}
				/**
				 * Redirect
				 */
				$result['message'] = $this->view->translate('mail_feedback_send_successfull');
				$result['status'] = true;
					
				$this->getResponse()->setBody(Zend_Json::encode($result));
			} else {
				$result['message'] = $this->view->translate('mail_feedback_captcha_error');
				$result['status'] = false;
				
			}
		}else{
			$result['message'] = $this->view->translate('mail_feedback_send_error');
			$result['status'] = false;
		}
		$this->getResponse()->setBody(Zend_Json::encode($result));
	}
}
